from django.shortcuts import render
from .models import City, Itinerary, PredictInfor, PredictInfordate
from .serializers import ItinerarySerializer
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime,timedelta
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from django.utils import timezone
from django.conf import settings
import json
import os
import pandas as pd
import jwt
from jwt.exceptions import ExpiredSignatureError, InvalidTokenError
from django.db.models import  Count


@csrf_exempt
# Create your views here.
def geoCoordMap(request):
    auth_header = request.headers.get('Authorization')
    print(auth_header)
    if not auth_header:
        return JsonResponse({'error': 'Authorization header is missing'}, status=401)

    print(f'Authorization header: {auth_header}')
    try:
        token_str = auth_header.split(' ')[1]
        print(f'Token: {token_str}')
    except IndexError:
        return JsonResponse({'error': 'Token is not correctly formatted'}, status=401)

    try:
        # 验证并解码 JWT
        payload = jwt.decode(token_str, settings.SECRET_KEY, algorithms=['HS256'])
        user_id = payload['user_id']
        print(f'Authenticated user ID: {user_id}')

        # 获取城市数据
        cities = City.objects.all()
        print(cities)
        city_data = {city.city_name: [city.city_lon, city.city_lat] for city in cities}

        return JsonResponse(city_data, safe=False)
    except jwt.ExpiredSignatureError:
        print('Token has expired')
        return JsonResponse({'error': 'Token has expired'}, status=401)
    except jwt.InvalidTokenError as e:
        print(f'Invalid token: {e}')
        return JsonResponse({'error': 'Invalid token'}, status=401)
    except Exception as e:
        print(f'Unexpected error: {e}')
        import traceback
        traceback.print_exc()
        return JsonResponse({'error': str(e)}, status=500)
@csrf_exempt
def routes(request):
    print(request)
    try:
        all_routes = Itinerary.objects.all()[:100]
        data = []
        for route in all_routes:
            route_data = [
                {"name": route.departure_city, "time": route.arrival_date.strftime("%Y-%m-%d")},
                {"name": route.arrival_city, "value": route.price}
            ]
            data.append(route_data)

        return JsonResponse({"routes": data})
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

@csrf_exempt
def mapForm(request):
    print("res")
    try:
        if request.method == 'POST':
            print(os.getcwd())  # 获取当前工作目录路径
            data = json.loads(request.body)
            start_position = []
            aim_position = []
            date_str = []
            if data.get("startPosition"):
                start_position = data.get("startPosition")
                print(start_position)
            if data.get("aimPosition"):
                aim_position = data.get("aimPosition")
                print(aim_position)
            if data.get("Date"):
                date_str = data.get("Date")
                print(date_str)

            if start_position:
                flights = PredictInfor.objects.filter(
                    departure_city=start_position,
                )
                if aim_position:
                    flights = PredictInfor.objects.filter(
                        departure_city=start_position,
                        arrival_city=aim_position,
                    )
                    if date_str:
                        # 解析前端传回的日期字符串
                        date_obj = datetime.fromisoformat(date_str.replace('Z', '+00:00'))
                        date = date_obj.date()
                        time = date_obj.time()
                else:
                    if aim_position:
                        flights = PredictInfor.objects.filter(
                            departure_city=start_position,
                            arrival_city=aim_position,
                        )
                day_diff=1
                if date_str:
                    # 解析前端传回的日期字符串
                    date_2 = datetime.now().date()
                    date_1 = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fz").date()
                    print(date_1)
                    day_diff = (date_1 - date_2).days + 1

                flightInfor_list = []
                for flight in flights:
                    a = [flight.price1,flight.price2,flight.price3,flight.price4,flight.price5,flight.price6,flight.price7,flight.price8,flight.price9,flight.price10,flight.price11,flight.price12,flight.price13,flight.price14,flight.price15]
                    min_price = min(a[:day_diff])
                    min_index= [index for index, value in enumerate(a) if round(value) == round(min_price)]
                    flightInfor_list.append({
                        #'flight_no': flight.flight.flight_no,
                        'uid':flight.uid,
                        'airline': flight.airline,
                        #'duration': str(duration),
                        'price': round(min_price),
                        'startDate':(datetime.now()+timedelta(days=mindate)).strftime("%m-%d"),
                        'route': flight.departure_city + '-' + flight.arrival_city
                    })
                flightInfor_list.sort(key=lambda x: x['price'], reverse=False)
                return JsonResponse({
                    'status': 200,
                    'message': 'success',
                    'data': flightInfor_list
                })
            return JsonResponse({'status': 200, 'data': data})
    except Exception as e:
        print(str(e))
        return JsonResponse({'error': str(e)}, status=500)

@csrf_exempt
def predication(request):
    try:
        if request.method == 'POST':
            print("normal run")
            print(os.getcwd())  # 获取当前工作目录路径
            data = json.loads(request.body)
            print(data)
            if data.get("params"):
                print("good!")
                id=data.get("params")
                priceInfor=PredictInfor.objects.filter(uid=id['uid']).first()
                dateInfor=PredictInfordate.objects.filter(uid=id['uid']).first()
                print("objects exist")
                prices=[priceInfor.price1,priceInfor.price2,priceInfor.price3,priceInfor.price4,priceInfor.price5,priceInfor.price6,priceInfor.price7,priceInfor.price8,priceInfor.price9,priceInfor.price10,priceInfor.price11,priceInfor.price12,priceInfor.price13,priceInfor.price14,priceInfor.price15]
                print(prices)
                dates=[dateInfor.date1.strftime("%m-%d"),dateInfor.date2.strftime("%m-%d"),dateInfor.date3.strftime("%m-%d"),dateInfor.date4.strftime("%m-%d"),dateInfor.date5.strftime("%m-%d"),dateInfor.date6.strftime("%m-%d"),dateInfor.date7.strftime("%m-%d"),dateInfor.date8.strftime("%m-%d"),dateInfor.date9.strftime("%m-%d"),dateInfor.date10.strftime("%m-%d"),dateInfor.date11.strftime("%m-%d"),dateInfor.date12.strftime("%m-%d"),dateInfor.date13.strftime("%m-%d"),dateInfor.date14.strftime("%m-%d"),dateInfor.date15.strftime("%m-%d")]
                print(prices)
                return JsonResponse({
                    'status': 200,
                    'message': 'success',
                    'data':{
                        'prices':prices,
                        'dates':dates
                    }
                })
            return JsonResponse({'status': 400, 'message': '无效请求'})
    except Exception as e:
        print(str(e))
        return JsonResponse({'error': str(e)}, status=500)

@csrf_exempt
def RouteProfile(request):
    print(request)
    try:
        data = []
        city_counts = Itinerary.objects.values('departure_city').annotate(count=Count('departure_city')).order_by('count')
        data.append({"name":city_counts[0]["departure_city"],"value":city_counts[0]["count"]})
        data.append({"name": city_counts[1]["departure_city"], "value": city_counts[1]["count"]})
        data.append({"name": city_counts[2]["departure_city"], "value": city_counts[2]["count"]})
        data.append({"name": city_counts[3]["departure_city"], "value": city_counts[3]["count"]})
        #data.append({"name": city_counts[4]["departure_city"], "value": city_counts[4]["count"]})
        return JsonResponse({'status':200,'data':{'data':data}})

    except Exception as e:
        print("not good!")
        print(str(e))
        return JsonResponse({'error': str(e)}, status=500)

@csrf_exempt
def SearchAirlinenum(request):
    try:
        dates=[]
        counts=[]
        date_counts = Itinerary.objects.values('departure_date').annotate(count=Count('departure_date')).order_by('departure_date')
        num=0
        for items in date_counts:
            if num == 5:
                break
            dates.append(str(items['departure_date']))
            counts.append(items['count'])
            num=num+1

        return  JsonResponse({'status':200,
                              'data':{
                                  'dates':dates,
                                  'counts':counts
                              }
                })
    except Exception as e:
        print("not good for chart")
        print(str(e))
        return JsonResponse({'error': str(e)}, status=500)

@csrf_exempt
def popularDataFlight(request):
    try:
        city_counts = Itinerary.objects.values('flight_type').annotate(count=Count('flight_type')).order_by('count')

        return JsonResponse({"data":{
                                    "popularAircraft":city_counts[0]['flight_type'],
                                    "totalFlights":city_counts[0]['count']
                                }
        })
    except Exception as e:
        print(str(e))
        return JsonResponse({'error': str(e)}, status=500)

@csrf_exempt
def popularDataAirport(request):
    print(request)
    try:
        ''' cities = City.objects.all()
        # print(cities)
        name_value_list = []
        for city in cities:
            city_value = 0
            city_name = city.city_name
            # print(city_name)

            flights_end = Itinerary.objects.filter(arrival_city=city_name)
            # print(flights_end)
            for flight_end in flights_end:
                city_value = city_value + 1

            flights_begin = Itinerary.objects.filter(departure_city=city_name)
            # print(flights_begin)
            for flight_begin in flights_begin:
                city_value = city_value + 1

            name_value_list.append({city_name: city_value})

        # print("well")
        # print(name_value_list)
        name_value_list.sort(key=lambda x: list(x.values())[0], reverse=True)
        # print(name_value_list)
        # print("good")

        # print(data)'''
        airport_counts = Itinerary.objects.values('departure_airport').annotate(count=Count('departure_airport')+Count('departure_airport')).order_by('count')
        print(airport_counts[0]['departure_airport'])
        print(airport_counts[0]['count'])
        return JsonResponse({"data":{
                                    "popularAirplane":airport_counts[0]['departure_airport'],
                                    "totalLines":airport_counts[0]['count']
                                }
        })
    except Exception as e:
        print("not good!")
        print(str(e))
        return JsonResponse({'error': str(e)}, status=500)

@csrf_exempt
def searchflight(request):
    try:
        print("normal run")
        if request.method == 'POST':
            data = json.loads(request.body)
            flights = Itinerary.objects.filter(flight_no=data.get("searchFlightId")).first()
            start_datetime = datetime.combine(flights.departure_date, flights.departure_time)
            end_datetime = datetime.combine(flights.arrival_date, flights.arrival_time)
            duration = end_datetime - start_datetime
            flightInfor_list = []
            flightInfor_list.append({
                "airline": flights.airline,
                "price": flights.price,
                "duration": str(duration),
                "route": flights.departure_city + '-' + flights.arrival_city,
                "uid": flights.itinerary_id,
                "startDate": flights.departure_date,
                "airlineNum": flights.flight_no
            })
            print("good")
            print(flightInfor_list)
            print("well")
            return JsonResponse({
                'status': 200,
                'data': flightInfor_list
            })
    except Exception as e:
        print("not good!")
        print(str(e))
        return JsonResponse({'error': str(e)}, status=500)